%%%-------------------------------------------------------------------
%%% File    : ewgi_buffer.erl
%%% Author  : Filippo Pacini <pacini@sgconsulting.it>
%%% License :
%%% The contents of this file are subject to the Mozilla Public
%%% License Version 1.1 (the "License"); you may not use this file
%%% except in compliance with the License. You may obtain a copy of
%%% the License at http://www.mozilla.org/MPL/
%%%
%%% Software distributed under the License is distributed on an "AS IS"
%%% basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
%%% the License for the specific language governing rights and
%%% limitations under the License.
%%% The Initial Developer of the Original Code is S.G. Consulting
%%% srl. Portions created by S.G. Consulting s.r.l. are Copyright (C)
%%% 2007 S.G. Consulting srl. All Rights Reserved.
%%%
%%% @doc 
%%% <p>Implement a buffer like process to accumulate response data:
%%% headers and body.</p>
%%%
%%% @end
%%%
%%% Created : 19 Nov 2007 by Filippo Pacini <pacini@sgconsulting.it>
%%%-------------------------------------------------------------------
-module(ewgi_buffer).

%% API
-export([start/0, is_empty/1, append/2, close/1]).

-define(TIMEOUT, 3000).

start() ->
    spawn(fun() -> loop([]) end).

close(Pid) ->
    rpc(Pid, close).

is_empty(Pid) ->
    rpc(Pid, is_empty).

append(Pid, Obj) ->
    rpc(Pid, {append, Obj}).

rpc(Pid, Query) ->        
    Pid ! {self(), Query},
    receive
        {Pid, Resp} -> Resp
    after
        ?TIMEOUT -> {error, timeout}
    end.
            
%%====================================================================
%% Internal functions
%%====================================================================
loop(Buf) ->
    receive
        {From, {append, Obj}} ->
            From ! {self(), ok},
            loop([Obj|Buf]);
        {From, is_empty} ->
            From ! {self(), length(Buf)=:=0},
            loop(Buf);
        {From, close} ->
            From ! {self(), lists:reverse(Buf)}
    end.
